<template>
  <el-dialog
    v-model="props.visible"
    width="auto"
    destroy-on-close
    align-center
    :close-on-click-modal="false"
    @opened="handleDeviceDialogOpen"
    @close="handleDialogClose"
    :title="handleDialogTitle()">
    <div class="prompt-dialog">
      <div class="prompt-form">
        <el-form
          label-width="calc(80 / 1920* 100vw)"
          ref="promptFormRef"
          :model="promptForm"
          :rules="promptFormRules"
          :disabled="props.dialogMode !== 'edit' && props.dialogMode !== 'create'">
          <el-form-item
            label="名称"
            prop="name">
            <el-input
              :disabled="props.dialogMode === 'edit' && props.isPreset"
              v-model="promptForm.name"
              maxlength="10"
              show-word-limit
              placeholder="10个字以内"
              clearable>
            </el-input>
          </el-form-item>
          <el-form-item
            label="角色"
            prop="role">
            <el-input
              v-model="promptForm.role"
              placeholder="让AI扮演一个角色，例如：交通工程师"
              clearable>
            </el-input>
          </el-form-item>
          <el-form-item
            label="背景"
            prop="background">
            <el-input
              v-model="promptForm.background"
              placeholder="交代一下背景，例如：应用城市张家口，了解张家口一年内主要道路拥堵指数。"
              clearable>
            </el-input>
          </el-form-item>
          <el-form-item
            label="目标"
            prop="target">
            <el-input
              v-model="promptForm.target"
              placeholder="给他一个目标，例如：基于拥堵指数算法，判断城市异常拥堵道路。"
              clearable>
            </el-input>
          </el-form-item>
          <el-form-item
            label="格式输出"
            prop="formattedOutput">
            <el-input
              type="textarea"
              v-model="promptForm.formattedOutput"
              :placeholder="`结果的呈现形式，例如：\n标题：《交通安全知识宣传》\n正文：-\n落款：-`"
              :autosize="{ minRows: 3, maxRows: 5 }"
              clearable>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <div
        class="btn-group"
        v-if="props.dialogMode !== 'check'">
        <el-button @click="quitCreatePrompt">取消</el-button>
        <el-button
          type="primary"
          @click="confirmCreatePrompt(promptFormRef)"
          >确认</el-button
        >
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
  import { getCurrentInstance, ref, reactive, onMounted, watch } from 'vue'
  import tipMessage from '@/utils/tipMessage'

  const emit = defineEmits(['handleDialogClose', 'refreshList'])
  const { proxy } = getCurrentInstance()
  const props = defineProps({
    visible: {
      type: Boolean,
      default: false
    },
    dialogMode: {
      type: String,
      default: ''
    },
    formData: {
      type: Object,
      default: {}
    }
  })
  const promptForm = reactive({
    name: '',
    role: '',
    background: '',
    target: '',
    formattedOutput: ''
  })
  const promptFormRules = reactive({
    name: [{ required: true, message: '请输入名称', trigger: ['blur', 'change'] }],
    role: [{ required: false, message: '请输入角色', trigger: ['blur', 'change'] }],
    background: [{ required: false, message: '请填写背景信息', trigger: ['blur', 'change'] }],
    target: [{ required: false, message: '请填写目标', trigger: ['blur', 'change'] }],
    formattedOutput: [{ required: false, message: '请填写输出格式', trigger: ['blur', 'change'] }]
  })
  const promptFormRef = ref(null)
  /* =========方法========== */
  const handleDialogTitle = () => {
    if (props.dialogMode === 'edit') {
      return '编辑提示词'
    } else if (props.dialogMode === 'check') {
      return '查看提示词'
    } else {
      return '新增提示词'
    }
  }
  const handleDialogClose = () => {
    emit('handleDialogClose', false)
    clearFormData()
  }
  const quitCreatePrompt = () => {
    emit('handleDialogClose', false)
    clearFormData()
  }
  const confirmCreatePrompt = formEl => {
    if (!formEl) return
    formEl.validate(valid => {
      if (valid) {
        if (props.dialogMode === 'create') {
          addPrompt()
            .then(() => {
              // emit('handleDialogClose', false)
              // emit('refreshList')
              // clearFormData()
              // tipMessage('创建成功', 'success')
            })
            .catch(error => {
              console.error('创建失败:', error)
            })
        } else if (props.dialogMode === 'edit') {
          updatePrompt()
            .then(() => {
              // emit('handleDialogClose', false)
              // emit('refreshList')
              // clearFormData()
              // tipMessage('更新成功', 'success')
            })
            .catch(error => {
              console.error('更新失败:', error)
            })
        }
      } else {
        console.log('error submit!')
      }
    })
  }
  const updatePrompt = async () => {
    try {
      const res = await proxy.$http.postWithBody('prompt/update', promptForm)
      emit('handleDialogClose', false)
      emit('refreshList')
      clearFormData()
      tipMessage('更新成功', 'success')
    } catch (error) {
      console.log(error)
      throw error
    }
  }
  const addPrompt = async () => {
    try {
      const res = await proxy.$http.postWithBody('prompt/insert', promptForm)
      emit('handleDialogClose', false)
      emit('refreshList')
      clearFormData()
      tipMessage('创建成功', 'success')
    } catch (error) {
      console.log(error)
      throw error
    }
  }
  const clearFormData = () => {
    promptForm.name = ''
    promptForm.role = ''
    promptForm.background = ''
    promptForm.target = ''
    promptForm.formattedOutput = ''
  }
  const handleDeviceDialogOpen = () => {}

  watch(
    () => props.formData,
    (newVal, oldVal) => {
      if (props.dialogMode === 'edit' || props.dialogMode === 'check') {
        for (const key in newVal) {
          promptForm[key] = newVal[key]
        }
      }
    }
  )
  watch(
    () => props.dialogMode,
    (newVal, oldVal) => {
      if (newVal === 'check') {
        promptFormRules.name[0].required = false
      } else {
        promptFormRules.name[0].required = true
      }
    }
  )
  onMounted(() => {})
</script>

<style scoped lang="scss">
  .prompt-dialog {
    width: pxTvw(1200);
    display: flex;
    flex-wrap: wrap;
    justify-content: center;

    & > .prompt-form {
      width: pxTvw(1168);
      // height: pxTvh(360);
      margin-top: pxTvh(16);
      .el-form {
        display: flex;
        flex-direction: column;
        .el-form-item {
          margin-bottom: pxTvh(24);
          :deep(.el-input__wrapper) {
            height: pxTvh(40);
            border-radius: 4px;
          }
        }
        .el-form-item:last-child {
          align-items: start;
          :deep(.el-form-item__label) {
            line-height: 18px;
          }
        }
      }
    }

    & > .btn-group {
      margin-top: pxTvh(24);
      display: flex;
      justify-content: end;
      margin-right: pxTvh(20);
      margin-left: auto;
      .el-button {
        height: pxTvh(40);
      }
    }
    :deep(.el-input__count-inner) {
      background-color: transparent;
    }
  }
</style>
